package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;


    @Override
    public R deleteById(Long id) {

        //1、检查该分类下是否有对应的菜品数据，有则不能删除
        LambdaQueryWrapper<Dish> dishqw = new LambdaQueryWrapper<>();
        dishqw.eq(Dish::getCategoryId,id);
        Integer count = dishMapper.selectCount(dishqw);
        if(count>0){
            return R.error("当前分类下有菜品，不能删除！！");
        }

        //2、检查该分类下是否有对应的套餐数据，有则不能删除
        LambdaQueryWrapper<Setmeal> setmealqw = new LambdaQueryWrapper<>();
        setmealqw.eq(Setmeal::getCategoryId,id);
        count = setmealMapper.selectCount(setmealqw);
        if(count>0){
            return R.error("当前分类下有套餐，不能删除！！");
        }

        //3、删除分类
        int delete = categoryMapper.deleteById(id);


        return delete>0?R.success("分类删除成功"):R.error("分类删除失败");
    }

    @Override
    public R deleteByIds(List<Long> ids) {
        if(CollUtil.isEmpty(ids)){
            return R.error("请选择需要删除的套餐！");
        }

        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(Setmeal::getStatus,1);
        qw.in(Setmeal::getId,ids);
        int count = setmealMapper.selectCount(qw);
        if(count>0){
            return R.error("有正在售卖的套餐，不允许删除！");
        }

        // 套餐对应的菜品数据 delete from setmeal_dish where setmeal_id in  (1,2,3)
        LambdaQueryWrapper<SetmealDish> qw2 = new LambdaQueryWrapper<>();
        qw2.in(SetmealDish::getSetmealId,ids);
        setmealDishMapper.delete(qw2);

        // 删除套餐
        int result = setmealMapper.deleteBatchIds(ids);


        return result>0?R.success("删除套餐成功！"):R.error("删除套餐失败！");
    }
}
